package com.zyh.scs.common.core.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 明确异步线程池配置，避免和 @EnableScheduling 造成的线程池冲突
 *
 * @author scs
 * @date 2024/4/20
 */
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class AsyncConfiguration implements AsyncConfigurer {

    private final ThreadPoolTaskExecutor applicationTaskExecutor;

    @Override
    public Executor getAsyncExecutor() {
        return applicationTaskExecutor;
    }

    /**
     * 线程池核心池的大小
     */
    @Value("${threadPool.corePoolSize}")
    private String corePoolSize;

    /**
     * 线程池最大线程数
     */
    @Value("${threadPool.maxPoolSize}")
    private String maxPoolSize;

    /**
     * 阻塞队列容量
     */
    @Value("${threadPool.queueCapacity}")
    private String queueCapacity;

    /**
     * 活跃时间
     */
    @Value("${threadPool.keepAliveSeconds}")
    private String keepAliveSeconds;


    //获取CPU核数
    static int cpuNums = Runtime.getRuntime().availableProcessors();

    /**
     * 创建线程池
     *
     * @return
     */
    @Bean("ScsExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        applicationTaskExecutor.setCorePoolSize(Integer.parseInt(corePoolSize));
        applicationTaskExecutor.setMaxPoolSize(Integer.parseInt(maxPoolSize));
        applicationTaskExecutor.setKeepAliveSeconds(Integer.parseInt(keepAliveSeconds));
        applicationTaskExecutor.setQueueCapacity(Integer.parseInt(queueCapacity));
        // 直接在execute方法的调用线程中运行
        applicationTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        applicationTaskExecutor.initialize();
        return applicationTaskExecutor;
    }
}
